package lis.r1.wyd1;

public class WatkiDwaPlusJeden implements Runnable {

	private int whichThread;
	private int delay;
	private static int account = 0;
	private static Object semafor;

	public WatkiDwaPlusJeden(int whichThread, int delay) {
		this.whichThread = whichThread;
		this.delay = delay;
	}

	public WatkiDwaPlusJeden() {
		super();
	}

	@Override
	public void run() {

		switch (whichThread) {
		case 1:
			thread1();
			break;
		case 2:
			thread2();
			break;
		case 3:
			thread3();
			break;
		}
	}

	private void thread1() {

		int temp;
		for (int i = 0; i < 5; i++) {
			synchronized (semafor) {
				temp = account;
				// System.out.println(Thread.currentThread().getName() + " " +
				// account);
				try {
					Thread.sleep(delay);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				account = temp + 1;
				System.out.println(Thread.currentThread().getName() + " "
						+ account);
			}
		}
	}

	private void thread2() {

		int temp;
		for (int i = 0; i < 5; i++) {
			synchronized (semafor) {
				temp = account;
				// System.out.println(Thread.currentThread().getName() + " " +
				// account);
				try {
					Thread.sleep(delay);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				account = temp + 1;
				System.out.println(Thread.currentThread().getName() + " "
						+ account);
			}
		}
	}

	private void thread3() {

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Account = " + account);

	}

	public static void main(String[] args) {

		semafor = new Object();
		new Thread(new WatkiDwaPlusJeden(1, 200)).start();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(new WatkiDwaPlusJeden(2, 100)).start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(new WatkiDwaPlusJeden(3, 0)).start();
	}

}
